/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.pku.hawk.cloud.cluster;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import edu.pku.hawk.cloud.util.CloudCfg;
import edu.pku.hawk.cloud.util.XenUtil;

/**
 *
 * @author Administrator
 */
public class ClusterController {

    public static Map createVmByName(String tplUuid, float cpuCap, float memCap, float diskCap, float net) {
        Map result = new HashMap();
        String masterIP = CloudCfg.POOL_MASTER_IP;
//        String tplUuid = "9fe9c9ad-1aee-78d1-8eeb-5275f85df98d";//CentOS_5.3_TPL
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        String newvmname = "VM_CJ" + dateString;

        memCap += (float)512;
        Map vmInfo = XenUtil.createVm(masterIP, tplUuid, newvmname, memCap);
        result.put("VM_IP", vmInfo.get("IP"));
        result.put("HOST_NAME", vmInfo.get("HOST_NAME"));
        result.put("VM_NAME", newvmname);
        return result;
    }

    public static String createVmOnByName(String tplUuid, float cpuCap, float memCap, float diskCap, float net, String hostName) {
        String masterIP = CloudCfg.POOL_MASTER_IP;

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        String newvmname = "VM" + dateString;
        Map vmInfo = XenUtil.createVmOn(masterIP, tplUuid, newvmname, memCap, hostName);
        return (String) vmInfo.get("VM_IP");
    }

    public static Boolean startVmByName(String vmName) {
        String masterIP = CloudCfg.POOL_MASTER_IP;
        XenUtil.startVmByName(masterIP, vmName);
        return true;
    }

    public static Boolean startVmOnHostByName(String vmName, String hostName) {
        String masterIP = CloudCfg.POOL_MASTER_IP;
        XenUtil.startVmOnByName(masterIP, vmName, hostName);

        return true;
    }

    public static Boolean stopVmByName(String vmName) {
        String masterIP = CloudCfg.POOL_MASTER_IP;
        XenUtil.stopVmByName(masterIP, vmName);
        return true;
    }

    public static void main(String[] args) {
        float cpuCap = 0;
        float memCap = 256;
        float diskCap = 0;
        float net = 0;
        String tplUuid = "be3c9408-9a86-86d8-e56f-fd92d366f9c4";
        Map createResult = ClusterController.createVmByName(tplUuid, cpuCap, memCap, diskCap, net);
        System.out.println("VM_IP:" + (String) createResult.get("VM_IP"));
        System.out.println("HOST_NAME:" + (String) createResult.get("HOST_NAME"));
        System.out.println("VM_NAME:" + (String) createResult.get("VM_NAME"));

//        ClusterController.startVmByName("CentOS5_vm001");
//        ClusterController.stopVmByName("CentOS5_vm001");
    }
}
